package com.david.rabbitdlq.service;

import com.alibaba.fastjson.JSON;
import com.david.rabbitdlq.config.RabbitConfig;
import com.david.rabbitdlq.dao.OrderRepository;
import com.david.rabbitdlq.entity.Order;
import com.david.rabbitdlq.entity.OrderStatus;
import com.david.rabbitdlq.util.OrderHelper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class OrderListener {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    //死信队列中删除rediskey 和将订单状态改成失败
    @RabbitListener(queues = RabbitConfig.DL_QUEUE)
    public void listenDlq(@Payload String o, @Headers Map<String, Object> properties, Channel channel) {
        log.info("receive expire paying order:{}", o);
        Order order = JSON.parseObject(o, Order.class);
        order.setStatus(OrderStatus.failed.name());
        orderRepository.save(order);
        redisTemplate.delete(OrderHelper.key(String.valueOf(order.getId())));
    }
}
